using System;
using System.Collections.Concurrent;
using System.IO;
using System.Threading.Tasks;
using EntityKit.Runtime;
using UnityEngine;

/// <summary>
/// StorageKit主类，提供统一访问入口
/// </summary>
public static class StorageKit
{
    private static string _storagePath;
    private static IDataSerializer _serializer;
    private static IEncryptionProvider _encryptionProvider;
    private static IPlatformStorageAdapter _platformAdapter;
    private static bool _initialized = false;

    // 简单类型的内存缓存
    private static readonly ConcurrentDictionary<string, int> _intCache = new ConcurrentDictionary<string, int>();
    private static readonly ConcurrentDictionary<string, float> _floatCache = new ConcurrentDictionary<string, float>();
    private static readonly ConcurrentDictionary<string, string> _stringCache = new ConcurrentDictionary<string, string>();
    private static readonly ConcurrentDictionary<string, bool> _boolCache = new ConcurrentDictionary<string, bool>();
    private static readonly ConcurrentDictionary<string, double> _doubleCache = new ConcurrentDictionary<string, double>();
    private static readonly ConcurrentDictionary<string, long> _longCache = new ConcurrentDictionary<string, long>();

    // Unity类型的内存缓存
    private static readonly ConcurrentDictionary<string, SerializableVector2> _vector2Cache = new ConcurrentDictionary<string, SerializableVector2>();
    private static readonly ConcurrentDictionary<string, SerializableVector3> _vector3Cache = new ConcurrentDictionary<string, SerializableVector3>();
    private static readonly ConcurrentDictionary<string, SerializableColor> _colorCache = new ConcurrentDictionary<string, SerializableColor>();
    private static readonly ConcurrentDictionary<string, SerializableVector4> _vector4Cache = new ConcurrentDictionary<string, SerializableVector4>();
    private static readonly ConcurrentDictionary<string, SerializableQuaternion> _quaternionCache = new ConcurrentDictionary<string, SerializableQuaternion>();
    private static readonly ConcurrentDictionary<string, SerializableRect> _rectCache = new ConcurrentDictionary<string, SerializableRect>();

    // 自定义对象缓存
    private static readonly ConcurrentDictionary<string, object> _objectCache = new ConcurrentDictionary<string, object>();

    #region 初始化和配置方法

    /// <summary>
    /// 初始化StorageKit
    /// </summary>
    /// <param name="config">配置对象</param>
    public static void Initialize(StorageKitConfig config)
    {
        if (config == null)
            throw new ArgumentNullException(nameof(config));

        if (!config.Validate())
            throw new ArgumentException("Invalid configuration");

        _storagePath = Path.Combine(Application.persistentDataPath, "Storage", config.StorageSubPath);

        if (!Directory.Exists(_storagePath))
        {
            Directory.CreateDirectory(_storagePath);
        }

        _serializer = config.Serializer;
        _encryptionProvider = config.EncryptionProvider;
        _platformAdapter = config.PlatformAdapter;
        _initialized = true;
    }

    /// <summary>
    /// 释放资源
    /// </summary>
    public static void Release()
    {
        _serializer = null;
        _encryptionProvider = null;
        _platformAdapter = null;
        _storagePath = null;
        _initialized = false;

        // 清空所有缓存
        ClearAllCaches();
    }

    /// <summary>
    /// 设置数据序列化器
    /// </summary>
    /// <param name="serializer">序列化器</param>
    public static void SetSerializer(IDataSerializer serializer)
    {
        _serializer = serializer ?? throw new ArgumentNullException(nameof(serializer));
    }

    /// <summary>
    /// 设置加密提供者
    /// </summary>
    /// <param name="encryptionProvider">加密提供者</param>
    public static void SetEncryptionProvider(IEncryptionProvider encryptionProvider)
    {
        _encryptionProvider = encryptionProvider ?? throw new ArgumentNullException(nameof(encryptionProvider));
    }

    /// <summary>
    /// 设置平台适配器
    /// </summary>
    /// <param name="platformAdapter">平台适配器</param>
    public static void SetPlatformAdapter(IPlatformStorageAdapter platformAdapter)
    {
        _platformAdapter = platformAdapter ?? throw new ArgumentNullException(nameof(platformAdapter));
    }

    #endregion

    #region 基本数据类型方法

    /// <summary>
    /// 设置整数值
    /// </summary>
    /// <param name="key">键名</param>
    /// <param name="value">整数值</param>
    public static void SetInt(string key, int value)
    {
        try
        {
            CheckInitialized();
            _intCache.AddOrUpdate(key, value, (k, oldValue) => value);
            SaveData(key, value);
        }
        catch (Exception ex)
        {
            Debug.LogError($"设置整数值失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 获取整数值
    /// </summary>
    /// <param name="key">键名</param>
    /// <param name="defaultValue">默认值</param>
    /// <returns>整数值</returns>
    public static int GetInt(string key, int defaultValue = 0)
    {
        try
        {
            CheckInitialized();

            // 首先检查内存缓存
            if (_intCache.TryGetValue(key, out int cachedValue))
            {
                return cachedValue;
            }

            // 从存储中加载
            int value = LoadData(key, defaultValue);

            // 更新缓存
            _intCache.AddOrUpdate(key, value, (k, oldValue) => value);

            return value;
        }
        catch (Exception ex)
        {
            Debug.LogError($"获取整数值失败: {ex.Message}");
            return defaultValue;
        }
    }

    /// <summary>
    /// 设置浮点数值
    /// </summary>
    /// <param name="key">键名</param>
    /// <param name="value">浮点数值</param>
    public static void SetFloat(string key, float value)
    {
        try
        {
            CheckInitialized();
            _floatCache.AddOrUpdate(key, value, (k, oldValue) => value);
            SaveData(key, value);
        }
        catch (Exception ex)
        {
            Debug.LogError($"设置浮点数值失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 获取浮点数值
    /// </summary>
    /// <param name="key">键名</param>
    /// <param name="defaultValue">默认值</param>
    /// <returns>浮点数值</returns>
    public static float GetFloat(string key, float defaultValue = 0f)
    {
        try
        {
            CheckInitialized();

            // 首先检查内存缓存
            if (_floatCache.TryGetValue(key, out float cachedValue))
            {
                return cachedValue;
            }

            // 从存储中加载
            float value = LoadData(key, defaultValue);

            // 更新缓存
            _floatCache.AddOrUpdate(key, value, (k, oldValue) => value);

            return value;
        }
        catch (Exception ex)
        {
            Debug.LogError($"获取浮点数值失败: {ex.Message}");
            return defaultValue;
        }
    }

    /// <summary>
    /// 设置字符串值
    /// </summary>
    /// <param name="key">键名</param>
    /// <param name="value">字符串值</param>
    public static void SetString(string key, string value)
    {
        try
        {
            CheckInitialized();
            _stringCache.AddOrUpdate(key, value, (k, oldValue) => value);
            SaveData(key, value);
        }
        catch (Exception ex)
        {
            Debug.LogError($"设置字符串值失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 获取字符串值
    /// </summary>
    /// <param name="key">键名</param>
    /// <param name="defaultValue">默认值</param>
    /// <returns>字符串值</returns>
    public static string GetString(string key, string defaultValue = "")
    {
        try
        {
            CheckInitialized();

            // 首先检查内存缓存
            if (_stringCache.TryGetValue(key, out string cachedValue))
            {
                return cachedValue;
            }

            // 从存储中加载
            string value = LoadData(key, defaultValue);

            // 更新缓存
            _stringCache.AddOrUpdate(key, value, (k, oldValue) => value);

            return value;
        }
        catch (Exception ex)
        {
            Debug.LogError($"获取字符串值失败: {ex.Message}");
            return defaultValue;
        }
    }

    /// <summary>
    /// 设置布尔值
    /// </summary>
    /// <param name="key">键名</param>
    /// <param name="value">布尔值</param>
    public static void SetBool(string key, bool value)
    {
        try
        {
            CheckInitialized();
            _boolCache.AddOrUpdate(key, value, (k, oldValue) => value);
            SaveData(key, value);
        }
        catch (Exception ex)
        {
            Debug.LogError($"设置布尔值失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 获取布尔值
    /// </summary>
    /// <param name="key">键名</param>
    /// <param name="defaultValue">默认值</param>
    /// <returns>布尔值</returns>
    public static bool GetBool(string key, bool defaultValue = false)
    {
        try
        {
            CheckInitialized();

            // 首先检查内存缓存
            if (_boolCache.TryGetValue(key, out bool cachedValue))
            {
                return cachedValue;
            }

            // 从存储中加载
            bool value = LoadData(key, defaultValue);

            // 更新缓存
            _boolCache.AddOrUpdate(key, value, (k, oldValue) => value);

            return value;
        }
        catch (Exception ex)
        {
            Debug.LogError($"获取布尔值失败: {ex.Message}");
            return defaultValue;
        }
    }

    /// <summary>
    /// 设置Double值
    /// </summary>
    public static void SetDouble(string key, double value)
    {
        try
        {
            CheckInitialized();
            _doubleCache.AddOrUpdate(key, value, (k, oldValue) => value);
            SaveData(key, value);
        }
        catch (Exception ex)
        {
            Debug.LogError($"设置Double值失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 获取Double值
    /// </summary>
    public static double GetDouble(string key, double defaultValue = 0d)
    {
        try
        {
            CheckInitialized();
            if (_doubleCache.TryGetValue(key, out double cachedValue))
                return cachedValue;

            double value = LoadData(key, defaultValue);
            _doubleCache.AddOrUpdate(key, value, (k, oldValue) => value);
            return value;
        }
        catch (Exception ex)
        {
            Debug.LogError($"获取Double值失败: {ex.Message}");
            return defaultValue;
        }
    }

    /// <summary>
    /// 设置Long值
    /// </summary>
    public static void SetLong(string key, long value)
    {
        try
        {
            CheckInitialized();
            _longCache.AddOrUpdate(key, value, (k, oldValue) => value);
            SaveData(key, value);
        }
        catch (Exception ex)
        {
            Debug.LogError($"设置Long值失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 获取Long值
    /// </summary>
    public static long GetLong(string key, long defaultValue = 0L)
    {
        try
        {
            CheckInitialized();
            if (_longCache.TryGetValue(key, out long cachedValue))
                return cachedValue;

            long value = LoadData(key, defaultValue);
            _longCache.AddOrUpdate(key, value, (k, oldValue) => value);
            return value;
        }
        catch (Exception ex)
        {
            Debug.LogError($"获取Long值失败: {ex.Message}");
            return defaultValue;
        }
    }

    #endregion

    #region Unity类型方法

    /// <summary>
    /// 设置Vector2值
    /// </summary>
    /// <param name="key">键名</param>
    /// <param name="value">Vector2值</param>
    public static void SetVector2(string key, Vector2 value)
    {
        try
        {
            CheckInitialized();
            var serializableVector2 = new SerializableVector2(value);
            _vector2Cache.AddOrUpdate(key, serializableVector2, (k, oldValue) => serializableVector2);
            SaveData(key, serializableVector2);
        }
        catch (Exception ex)
        {
            Debug.LogError($"设置Vector2值失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 获取Vector2值
    /// </summary>
    /// <param name="key">键名</param>
    /// <param name="defaultValue">默认值</param>
    /// <returns>Vector2值</returns>
    public static Vector2 GetVector2(string key, Vector2 defaultValue = default)
    {
        try
        {
            CheckInitialized();

            // 首先检查内存缓存
            if (_vector2Cache.TryGetValue(key, out SerializableVector2 cachedValue))
            {
                return cachedValue.ToVector2();
            }

            // 从存储中加载
            var serializableVector2 = LoadData<SerializableVector2>(key, new SerializableVector2(defaultValue));

            // 更新缓存
            _vector2Cache.AddOrUpdate(key, serializableVector2, (k, oldValue) => serializableVector2);

            return serializableVector2.ToVector2();
        }
        catch (Exception ex)
        {
            Debug.LogError($"获取Vector2值失败: {ex.Message}");
            return defaultValue;
        }
    }

    /// <summary>
    /// 设置Vector3值
    /// </summary>
    /// <param name="key">键名</param>
    /// <param name="value">Vector3值</param>
    public static void SetVector3(string key, Vector3 value)
    {
        try
        {
            CheckInitialized();
            var serializableVector3 = new SerializableVector3(value);
            _vector3Cache.AddOrUpdate(key, serializableVector3, (k, oldValue) => serializableVector3);
            SaveData(key, serializableVector3);
        }
        catch (Exception ex)
        {
            Debug.LogError($"设置Vector3值失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 获取Vector3值
    /// </summary>
    /// <param name="key">键名</param>
    /// <param name="defaultValue">默认值</param>
    /// <returns>Vector3值</returns>
    public static Vector3 GetVector3(string key, Vector3 defaultValue = default)
    {
        try
        {
            CheckInitialized();

            // 首先检查内存缓存
            if (_vector3Cache.TryGetValue(key, out SerializableVector3 cachedValue))
            {
                return cachedValue.ToVector3();
            }

            // 从存储中加载
            var serializableVector3 = LoadData<SerializableVector3>(key, new SerializableVector3(defaultValue));

            // 更新缓存
            _vector3Cache.AddOrUpdate(key, serializableVector3, (k, oldValue) => serializableVector3);

            return serializableVector3.ToVector3();
        }
        catch (Exception ex)
        {
            Debug.LogError($"获取Vector3值失败: {ex.Message}");
            return defaultValue;
        }
    }

    /// <summary>
    /// 设置Vector4值
    /// </summary>
    public static void SetVector4(string key, Vector4 value)
    {
        try
        {
            CheckInitialized();
            var serializableVector4 = new SerializableVector4(value);
            _vector4Cache.AddOrUpdate(key, serializableVector4, (k, oldValue) => serializableVector4);
            SaveData(key, serializableVector4);
        }
        catch (Exception ex)
        {
            Debug.LogError($"设置Vector4值失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 获取Vector4值
    /// </summary>
    public static Vector4 GetVector4(string key, Vector4 defaultValue = default)
    {
        try
        {
            CheckInitialized();
            if (_vector4Cache.TryGetValue(key, out SerializableVector4 cachedValue))
                return cachedValue.ToVector4();

            var serializableVector4 = LoadData<SerializableVector4>(key, new SerializableVector4(defaultValue));
            _vector4Cache.AddOrUpdate(key, serializableVector4, (k, oldValue) => serializableVector4);
            return serializableVector4.ToVector4();
        }
        catch (Exception ex)
        {
            Debug.LogError($"获取Vector4值失败: {ex.Message}");
            return defaultValue;
        }
    }

    /// <summary>
    /// 设置Quaternion值
    /// </summary>
    public static void SetQuaternion(string key, Quaternion value)
    {
        try
        {
            CheckInitialized();
            var serializableQuaternion = new SerializableQuaternion(value);
            _quaternionCache.AddOrUpdate(key, serializableQuaternion, (k, oldValue) => serializableQuaternion);
            SaveData(key, serializableQuaternion);
        }
        catch (Exception ex)
        {
            Debug.LogError($"设置Quaternion值失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 获取Quaternion值
    /// </summary>
    public static Quaternion GetQuaternion(string key, Quaternion defaultValue = default)
    {
        try
        {
            CheckInitialized();
            if (_quaternionCache.TryGetValue(key, out SerializableQuaternion cachedValue))
                return cachedValue.ToQuaternion();

            var serializableQuaternion = LoadData<SerializableQuaternion>(key, new SerializableQuaternion(defaultValue));
            _quaternionCache.AddOrUpdate(key, serializableQuaternion, (k, oldValue) => serializableQuaternion);
            return serializableQuaternion.ToQuaternion();
        }
        catch (Exception ex)
        {
            Debug.LogError($"获取Quaternion值失败: {ex.Message}");
            return defaultValue;
        }
    }

    /// <summary>
    /// 设置Rect值
    /// </summary>
    public static void SetRect(string key, Rect value)
    {
        try
        {
            CheckInitialized();
            var serializableRect = new SerializableRect(value);
            _rectCache.AddOrUpdate(key, serializableRect, (k, oldValue) => serializableRect);
            SaveData(key, serializableRect);
        }
        catch (Exception ex)
        {
            Debug.LogError($"设置Rect值失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 获取Rect值
    /// </summary>
    public static Rect GetRect(string key, Rect defaultValue = default)
    {
        try
        {
            CheckInitialized();
            if (_rectCache.TryGetValue(key, out SerializableRect cachedValue))
                return cachedValue.ToRect();

            var serializableRect = LoadData<SerializableRect>(key, new SerializableRect(defaultValue));
            _rectCache.AddOrUpdate(key, serializableRect, (k, oldValue) => serializableRect);
            return serializableRect.ToRect();
        }
        catch (Exception ex)
        {
            Debug.LogError($"获取Rect值失败: {ex.Message}");
            return defaultValue;
        }
    }

    /// <summary>
    /// 设置Color值
    /// </summary>
    /// <param name="key">键名</param>
    /// <param name="value">Color值</param>
    public static void SetColor(string key, Color value)
    {
        try
        {
            CheckInitialized();
            var serializableColor = new SerializableColor(value);
            _colorCache.AddOrUpdate(key, serializableColor, (k, oldValue) => serializableColor);
            SaveData(key, serializableColor);
        }
        catch (Exception ex)
        {
            Debug.LogError($"设置Color值失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 获取Color值
    /// </summary>
    /// <param name="key">键名</param>
    /// <param name="defaultValue">默认值</param>
    /// <returns>Color值</returns>
    public static Color GetColor(string key, Color defaultValue = default)
    {
        try
        {
            CheckInitialized();

            // 首先检查内存缓存
            if (_colorCache.TryGetValue(key, out SerializableColor cachedValue))
            {
                return cachedValue.ToColor();
            }

            // 从存储中加载
            var serializableColor = LoadData<SerializableColor>(key, new SerializableColor(defaultValue));

            // 更新缓存
            _colorCache.AddOrUpdate(key, serializableColor, (k, oldValue) => serializableColor);

            return serializableColor.ToColor();
        }
        catch (Exception ex)
        {
            Debug.LogError($"获取Color值失败: {ex.Message}");
            return defaultValue;
        }
    }

    #endregion

    #region 自定义对象方法

    /// <summary>
    /// 设置自定义对象（自动序列化）
    /// </summary>
    public static void SetObject<T>(string key, T obj) where T : class
    {
        try
        {
            CheckInitialized();
            _objectCache.AddOrUpdate(key, obj, (k, oldValue) => obj);
            SaveData(key, obj);
        }
        catch (Exception ex)
        {
            Debug.LogError($"设置对象失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 获取自定义对象
    /// </summary>
    public static T GetObject<T>(string key, T defaultValue = null) where T : class
    {
        try
        {
            CheckInitialized();

            // 检查缓存
            if (_objectCache.TryGetValue(key, out object cachedObj) && cachedObj is T cachedT)
                return cachedT;

            // 从存储加载
            T value = LoadData<T>(key, defaultValue);
            if (value != null)
                _objectCache.AddOrUpdate(key, value, (k, oldValue) => value);

            return value;
        }
        catch (Exception ex)
        {
            Debug.LogError($"获取对象失败: {ex.Message}");
            return defaultValue;
        }
    }

    #endregion

    #region 异步基本数据类型方法

    /// <summary>
    /// 异步设置整数值
    /// </summary>
    /// <param name="key">键名</param>
    /// <param name="value">整数值</param>
    public static async Task SetIntAsync(string key, int value)
    {
        try
        {
            CheckInitialized();
            _intCache.AddOrUpdate(key, value, (k, oldValue) => value);
            await SaveDataAsync(key, value);
        }
        catch (Exception ex)
        {
            Debug.LogError($"异步设置整数值失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 异步获取整数值
    /// </summary>
    /// <param name="key">键名</param>
    /// <param name="defaultValue">默认值</param>
    /// <returns>整数值</returns>
    public static async Task<int> GetIntAsync(string key, int defaultValue = 0)
    {
        try
        {
            CheckInitialized();

            // 首先检查内存缓存
            if (_intCache.TryGetValue(key, out int cachedValue))
            {
                return cachedValue;
            }

            // 从存储中加载
            int value = await LoadDataAsync(key, defaultValue);

            // 更新缓存
            _intCache.AddOrUpdate(key, value, (k, oldValue) => value);

            return value;
        }
        catch (Exception ex)
        {
            Debug.LogError($"异步获取整数值失败: {ex.Message}");
            return defaultValue;
        }
    }

    /// <summary>
    /// 异步设置浮点数值
    /// </summary>
    /// <param name="key">键名</param>
    /// <param name="value">浮点数值</param>
    public static async Task SetFloatAsync(string key, float value)
    {
        try
        {
            CheckInitialized();
            _floatCache.AddOrUpdate(key, value, (k, oldValue) => value);
            await SaveDataAsync(key, value);
        }
        catch (Exception ex)
        {
            Debug.LogError($"异步设置浮点数值失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 异步获取浮点数值
    /// </summary>
    /// <param name="key">键名</param>
    /// <param name="defaultValue">默认值</param>
    /// <returns>浮点数值</returns>
    public static async Task<float> GetFloatAsync(string key, float defaultValue = 0f)
    {
        try
        {
            CheckInitialized();

            // 首先检查内存缓存
            if (_floatCache.TryGetValue(key, out float cachedValue))
            {
                return cachedValue;
            }

            // 从存储中加载
            float value = await LoadDataAsync(key, defaultValue);

            // 更新缓存
            _floatCache.AddOrUpdate(key, value, (k, oldValue) => value);

            return value;
        }
        catch (Exception ex)
        {
            Debug.LogError($"异步获取浮点数值失败: {ex.Message}");
            return defaultValue;
        }
    }

    /// <summary>
    /// 异步设置字符串值
    /// </summary>
    /// <param name="key">键名</param>
    /// <param name="value">字符串值</param>
    public static async Task SetStringAsync(string key, string value)
    {
        try
        {
            CheckInitialized();
            _stringCache.AddOrUpdate(key, value, (k, oldValue) => value);
            await SaveDataAsync(key, value);
        }
        catch (Exception ex)
        {
            Debug.LogError($"异步设置字符串值失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 异步获取字符串值
    /// </summary>
    /// <param name="key">键名</param>
    /// <param name="defaultValue">默认值</param>
    /// <returns>字符串值</returns>
    public static async Task<string> GetStringAsync(string key, string defaultValue = "")
    {
        try
        {
            CheckInitialized();

            // 首先检查内存缓存
            if (_stringCache.TryGetValue(key, out string cachedValue))
            {
                return cachedValue;
            }

            // 从存储中加载
            string value = await LoadDataAsync(key, defaultValue);

            // 更新缓存
            _stringCache.AddOrUpdate(key, value, (k, oldValue) => value);

            return value;
        }
        catch (Exception ex)
        {
            Debug.LogError($"异步获取字符串值失败: {ex.Message}");
            return defaultValue;
        }
    }

    /// <summary>
    /// 异步设置布尔值
    /// </summary>
    /// <param name="key">键名</param>
    /// <param name="value">布尔值</param>
    public static async Task SetBoolAsync(string key, bool value)
    {
        try
        {
            CheckInitialized();
            _boolCache.AddOrUpdate(key, value, (k, oldValue) => value);
            await SaveDataAsync(key, value);
        }
        catch (Exception ex)
        {
            Debug.LogError($"异步设置布尔值失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 异步获取布尔值
    /// </summary>
    /// <param name="key">键名</param>
    /// <param name="defaultValue">默认值</param>
    /// <returns>布尔值</returns>
    public static async Task<bool> GetBoolAsync(string key, bool defaultValue = false)
    {
        try
        {
            CheckInitialized();

            // 首先检查内存缓存
            if (_boolCache.TryGetValue(key, out bool cachedValue))
            {
                return cachedValue;
            }

            // 从存储中加载
            bool value = await LoadDataAsync(key, defaultValue);

            // 更新缓存
            _boolCache.AddOrUpdate(key, value, (k, oldValue) => value);

            return value;
        }
        catch (Exception ex)
        {
            Debug.LogError($"异步获取布尔值失败: {ex.Message}");
            return defaultValue;
        }
    }

    /// <summary>
    /// 异步设置Double值
    /// </summary>
    public static async Task SetDoubleAsync(string key, double value)
    {
        try
        {
            CheckInitialized();
            _doubleCache.AddOrUpdate(key, value, (k, oldValue) => value);
            await SaveDataAsync(key, value);
        }
        catch (Exception ex)
        {
            Debug.LogError($"异步设置Double值失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 异步获取Double值
    /// </summary>
    public static async Task<double> GetDoubleAsync(string key, double defaultValue = 0d)
    {
        try
        {
            CheckInitialized();
            if (_doubleCache.TryGetValue(key, out double cachedValue))
                return cachedValue;

            double value = await LoadDataAsync(key, defaultValue);
            _doubleCache.AddOrUpdate(key, value, (k, oldValue) => value);
            return value;
        }
        catch (Exception ex)
        {
            Debug.LogError($"异步获取Double值失败: {ex.Message}");
            return defaultValue;
        }
    }

    /// <summary>
    /// 异步设置Long值
    /// </summary>
    public static async Task SetLongAsync(string key, long value)
    {
        try
        {
            CheckInitialized();
            _longCache.AddOrUpdate(key, value, (k, oldValue) => value);
            await SaveDataAsync(key, value);
        }
        catch (Exception ex)
        {
            Debug.LogError($"异步设置Long值失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 异步获取Long值
    /// </summary>
    public static async Task<long> GetLongAsync(string key, long defaultValue = 0L)
    {
        try
        {
            CheckInitialized();
            if (_longCache.TryGetValue(key, out long cachedValue))
                return cachedValue;

            long value = await LoadDataAsync(key, defaultValue);
            _longCache.AddOrUpdate(key, value, (k, oldValue) => value);
            return value;
        }
        catch (Exception ex)
        {
            Debug.LogError($"异步获取Long值失败: {ex.Message}");
            return defaultValue;
        }
    }

    #endregion

    #region 异步Unity类型方法

    /// <summary>
    /// 异步设置Vector2值
    /// </summary>
    /// <param name="key">键名</param>
    /// <param name="value">Vector2值</param>
    public static async Task SetVector2Async(string key, Vector2 value)
    {
        try
        {
            CheckInitialized();
            var serializableVector2 = new SerializableVector2(value);
            _vector2Cache.AddOrUpdate(key, serializableVector2, (k, oldValue) => serializableVector2);
            await SaveDataAsync(key, serializableVector2);
        }
        catch (Exception ex)
        {
            Debug.LogError($"异步设置Vector2值失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 异步获取Vector2值
    /// </summary>
    /// <param name="key">键名</param>
    /// <param name="defaultValue">默认值</param>
    /// <returns>Vector2值</returns>
    public static async Task<Vector2> GetVector2Async(string key, Vector2 defaultValue = default)
    {
        try
        {
            CheckInitialized();

            // 首先检查内存缓存
            if (_vector2Cache.TryGetValue(key, out SerializableVector2 cachedValue))
            {
                return cachedValue.ToVector2();
            }

            // 从存储中加载
            var serializableVector2 = await LoadDataAsync<SerializableVector2>(key, new SerializableVector2(defaultValue));

            // 更新缓存
            _vector2Cache.AddOrUpdate(key, serializableVector2, (k, oldValue) => serializableVector2);

            return serializableVector2.ToVector2();
        }
        catch (Exception ex)
        {
            Debug.LogError($"异步获取Vector2值失败: {ex.Message}");
            return defaultValue;
        }
    }

    /// <summary>
    /// 异步设置Vector3值
    /// </summary>
    /// <param name="key">键名</param>
    /// <param name="value">Vector3值</param>
    public static async Task SetVector3Async(string key, Vector3 value)
    {
        try
        {
            CheckInitialized();
            var serializableVector3 = new SerializableVector3(value);
            _vector3Cache.AddOrUpdate(key, serializableVector3, (k, oldValue) => serializableVector3);
            await SaveDataAsync(key, serializableVector3);
        }
        catch (Exception ex)
        {
            Debug.LogError($"异步设置Vector3值失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 异步获取Vector3值
    /// </summary>
    /// <param name="key">键名</param>
    /// <param name="defaultValue">默认值</param>
    /// <returns>Vector3值</returns>
    public static async Task<Vector3> GetVector3Async(string key, Vector3 defaultValue = default)
    {
        try
        {
            CheckInitialized();

            // 首先检查内存缓存
            if (_vector3Cache.TryGetValue(key, out SerializableVector3 cachedValue))
            {
                return cachedValue.ToVector3();
            }

            // 从存储中加载
            var serializableVector3 = await LoadDataAsync<SerializableVector3>(key, new SerializableVector3(defaultValue));

            // 更新缓存
            _vector3Cache.AddOrUpdate(key, serializableVector3, (k, oldValue) => serializableVector3);

            return serializableVector3.ToVector3();
        }
        catch (Exception ex)
        {
            Debug.LogError($"异步获取Vector3值失败: {ex.Message}");
            return defaultValue;
        }
    }

    /// <summary>
    /// 异步设置Vector4值
    /// </summary>
    public static async Task SetVector4Async(string key, Vector4 value)
    {
        try
        {
            CheckInitialized();
            var serializableVector4 = new SerializableVector4(value);
            _vector4Cache.AddOrUpdate(key, serializableVector4, (k, oldValue) => serializableVector4);
            await SaveDataAsync(key, serializableVector4);
        }
        catch (Exception ex)
        {
            Debug.LogError($"异步设置Vector4值失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 异步获取Vector4值
    /// </summary>
    public static async Task<Vector4> GetVector4Async(string key, Vector4 defaultValue = default)
    {
        try
        {
            CheckInitialized();
            if (_vector4Cache.TryGetValue(key, out SerializableVector4 cachedValue))
                return cachedValue.ToVector4();

            var serializableVector4 = await LoadDataAsync<SerializableVector4>(key, new SerializableVector4(defaultValue));
            _vector4Cache.AddOrUpdate(key, serializableVector4, (k, oldValue) => serializableVector4);
            return serializableVector4.ToVector4();
        }
        catch (Exception ex)
        {
            Debug.LogError($"异步获取Vector4值失败: {ex.Message}");
            return defaultValue;
        }
    }

    /// <summary>
    /// 异步设置Quaternion值
    /// </summary>
    public static async Task SetQuaternionAsync(string key, Quaternion value)
    {
        try
        {
            CheckInitialized();
            var serializableQuaternion = new SerializableQuaternion(value);
            _quaternionCache.AddOrUpdate(key, serializableQuaternion, (k, oldValue) => serializableQuaternion);
            await SaveDataAsync(key, serializableQuaternion);
        }
        catch (Exception ex)
        {
            Debug.LogError($"异步设置Quaternion值失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 异步获取Quaternion值
    /// </summary>
    public static async Task<Quaternion> GetQuaternionAsync(string key, Quaternion defaultValue = default)
    {
        try
        {
            CheckInitialized();
            if (_quaternionCache.TryGetValue(key, out SerializableQuaternion cachedValue))
                return cachedValue.ToQuaternion();

            var serializableQuaternion = await LoadDataAsync<SerializableQuaternion>(key, new SerializableQuaternion(defaultValue));
            _quaternionCache.AddOrUpdate(key, serializableQuaternion, (k, oldValue) => serializableQuaternion);
            return serializableQuaternion.ToQuaternion();
        }
        catch (Exception ex)
        {
            Debug.LogError($"异步获取Quaternion值失败: {ex.Message}");
            return defaultValue;
        }
    }

    /// <summary>
    /// 异步设置Rect值
    /// </summary>
    public static async Task SetRectAsync(string key, Rect value)
    {
        try
        {
            CheckInitialized();
            var serializableRect = new SerializableRect(value);
            _rectCache.AddOrUpdate(key, serializableRect, (k, oldValue) => serializableRect);
            await SaveDataAsync(key, serializableRect);
        }
        catch (Exception ex)
        {
            Debug.LogError($"异步设置Rect值失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 异步获取Rect值
    /// </summary>
    public static async Task<Rect> GetRectAsync(string key, Rect defaultValue = default)
    {
        try
        {
            CheckInitialized();
            if (_rectCache.TryGetValue(key, out SerializableRect cachedValue))
                return cachedValue.ToRect();

            var serializableRect = await LoadDataAsync<SerializableRect>(key, new SerializableRect(defaultValue));
            _rectCache.AddOrUpdate(key, serializableRect, (k, oldValue) => serializableRect);
            return serializableRect.ToRect();
        }
        catch (Exception ex)
        {
            Debug.LogError($"异步获取Rect值失败: {ex.Message}");
            return defaultValue;
        }
    }

    /// <summary>
    /// 异步设置Color值
    /// </summary>
    /// <param name="key">键名</param>
    /// <param name="value">Color值</param>
    public static async Task SetColorAsync(string key, Color value)
    {
        try
        {
            CheckInitialized();
            var serializableColor = new SerializableColor(value);
            _colorCache.AddOrUpdate(key, serializableColor, (k, oldValue) => serializableColor);
            await SaveDataAsync(key, serializableColor);
        }
        catch (Exception ex)
        {
            Debug.LogError($"异步设置Color值失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 异步获取Color值
    /// </summary>
    /// <param name="key">键名</param>
    /// <param name="defaultValue">默认值</param>
    /// <returns>Color值</returns>
    public static async Task<Color> GetColorAsync(string key, Color defaultValue = default)
    {
        try
        {
            CheckInitialized();

            // 首先检查内存缓存
            if (_colorCache.TryGetValue(key, out SerializableColor cachedValue))
            {
                return cachedValue.ToColor();
            }

            // 从存储中加载
            var serializableColor = await LoadDataAsync<SerializableColor>(key, new SerializableColor(defaultValue));

            // 更新缓存
            _colorCache.AddOrUpdate(key, serializableColor, (k, oldValue) => serializableColor);

            return serializableColor.ToColor();
        }
        catch (Exception ex)
        {
            Debug.LogError($"异步获取Color值失败: {ex.Message}");
            return defaultValue;
        }
    }

    #endregion

    #region 异步自定义对象方法

    /// <summary>
    /// 异步设置自定义对象（自动序列化）
    /// </summary>
    public static async Task SetObjectAsync<T>(string key, T obj) where T : class
    {
        try
        {
            CheckInitialized();
            _objectCache.AddOrUpdate(key, obj, (k, oldValue) => obj);
            await SaveDataAsync(key, obj);
        }
        catch (Exception ex)
        {
            Debug.LogError($"异步设置对象失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 异步获取自定义对象
    /// </summary>
    public static async Task<T> GetObjectAsync<T>(string key, T defaultValue = null) where T : class
    {
        try
        {
            CheckInitialized();

            // 检查缓存
            if (_objectCache.TryGetValue(key, out object cachedObj) && cachedObj is T cachedT)
                return cachedT;

            // 从存储加载
            T value = await LoadDataAsync<T>(key, defaultValue);
            if (value != null)
                _objectCache.AddOrUpdate(key, value, (k, oldValue) => value);

            return value;
        }
        catch (Exception ex)
        {
            Debug.LogError($"异步获取对象失败: {ex.Message}");
            return defaultValue;
        }
    }

    #endregion

    #region 其他便捷方法

    /// <summary>
    /// 检查键是否存在
    /// </summary>
    /// <param name="key">键名</param>
    /// <returns>是否存在</returns>
    public static bool HasKey(string key)
    {
        return HasData(key);
    }

    /// <summary>
    /// 异步检查键是否存在
    /// </summary>
    /// <param name="key">键名</param>
    /// <returns>是否存在</returns>
    public static async Task<bool> HasKeyAsync(string key)
    {
        return await HasDataAsync(key);
    }

    /// <summary>
    /// 删除指定键的数据
    /// </summary>
    public static void DeleteKey(string key)
    {
        DeleteData(key);

        // 同时从所有缓存中移除
        _intCache.TryRemove(key, out _);
        _floatCache.TryRemove(key, out _);
        _stringCache.TryRemove(key, out _);
        _boolCache.TryRemove(key, out _);
        _doubleCache.TryRemove(key, out _);
        _longCache.TryRemove(key, out _);
        _vector2Cache.TryRemove(key, out _);
        _vector3Cache.TryRemove(key, out _);
        _vector4Cache.TryRemove(key, out _);
        _quaternionCache.TryRemove(key, out _);
        _rectCache.TryRemove(key, out _);
        _colorCache.TryRemove(key, out _);
        _objectCache.TryRemove(key, out _);
    }

    /// <summary>
    /// 异步删除指定键的数据
    /// </summary>
    public static async Task DeleteKeyAsync(string key)
    {
        await DeleteDataAsync(key);

        // 同时从所有缓存中移除
        _intCache.TryRemove(key, out _);
        _floatCache.TryRemove(key, out _);
        _stringCache.TryRemove(key, out _);
        _boolCache.TryRemove(key, out _);
        _doubleCache.TryRemove(key, out _);
        _longCache.TryRemove(key, out _);
        _vector2Cache.TryRemove(key, out _);
        _vector3Cache.TryRemove(key, out _);
        _vector4Cache.TryRemove(key, out _);
        _quaternionCache.TryRemove(key, out _);
        _rectCache.TryRemove(key, out _);
        _colorCache.TryRemove(key, out _);
        _objectCache.TryRemove(key, out _);
    }

    /// <summary>
    /// 删除所有数据
    /// </summary>
    public static void DeleteAll()
    {
        try
        {
            CheckInitialized();

            // 直接删除整个存储目录并重新创建，提高性能
            if (Directory.Exists(_storagePath))
            {
                Directory.Delete(_storagePath, true);
            }
            
            // 重新创建目录
            Directory.CreateDirectory(_storagePath);

            // 清空所有缓存
            ClearAllCaches();
        }
        catch (Exception ex)
        {
            Debug.LogError($"删除所有数据失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 异步删除所有数据
    /// </summary>
    public static async Task DeleteAllAsync()
    {
        try
        {
            CheckInitialized();

            // 使用Task.Run确保IO操作在线程池线程上执行，避免阻塞主线程
            await Task.Run(() =>
            {
                // 直接删除整个存储目录并重新创建，提高性能
                if (Directory.Exists(_storagePath))
                {
                    Directory.Delete(_storagePath, true);
                }

                // 重新创建目录
                Directory.CreateDirectory(_storagePath);
            });

            // 清空所有缓存
            ClearAllCaches();
        }
        catch (Exception ex)
        {
            Debug.LogError($"异步删除所有数据失败: {ex.Message}");
        }
    }

    #endregion

    #region 核心数据操作方法

    /// <summary>
    /// 保存数据
    /// </summary>
    /// <typeparam name="T">数据类型</typeparam>
    /// <param name="key">存储键</param>
    /// <param name="data">要存储的数据</param>
    public static void SaveData<T>(string key, T data)
    {
        try
        {
            CheckInitialized();
            string filePath = GetFilePath(key);
            string jsonData = _serializer.Serialize(data);
            string encryptedData = _encryptionProvider.Encrypt(jsonData);

            _platformAdapter.WriteFile(filePath, encryptedData);
        }
        catch (Exception ex)
        {
            Debug.LogError($"保存数据失败: {ex.Message}");
            throw new StorageException("保存数据失败", ex);
        }
    }

    /// <summary>
    /// 异步保存数据
    /// </summary>
    /// <typeparam name="T">数据类型</typeparam>
    /// <param name="key">存储键</param>
    /// <param name="data">要存储的数据</param>
    public static async Task SaveDataAsync<T>(string key, T data)
    {
        try
        {
            CheckInitialized();
            string filePath = GetFilePath(key);
            string jsonData = await _serializer.SerializeAsync(data);
            string encryptedData = await _encryptionProvider.EncryptAsync(jsonData);

            await _platformAdapter.WriteFileAsync(filePath, encryptedData);
        }
        catch (Exception ex)
        {
            Debug.LogError($"异步保存数据失败: {ex.Message}");
            throw new StorageException("异步保存数据失败", ex);
        }
    }

    /// <summary>
    /// 加载数据
    /// </summary>
    /// <typeparam name="T">数据类型</typeparam>
    /// <param name="key">存储键</param>
    /// <param name="defaultData">默认数据</param>
    /// <returns>加载的数据</returns>
    public static T LoadData<T>(string key, T defaultData = default(T))
    {
        try
        {
            CheckInitialized();
            string filePath = GetFilePath(key);

            if (!_platformAdapter.FileExists(filePath))
            {
                return defaultData;
            }

            string encryptedData = _platformAdapter.ReadFile(filePath);
            string jsonData = _encryptionProvider.Decrypt(encryptedData);

            return _serializer.Deserialize<T>(jsonData);
        }
        catch (FileNotFoundException)
        {
            // 文件不存在是预期行为，返回默认值
            return defaultData;
        }
        catch (Exception ex)
        {
            Debug.LogError($"加载数据失败: {ex.Message}");
            throw new StorageException("加载数据失败", ex);
        }
    }

    /// <summary>
    /// 异步加载数据
    /// </summary>
    /// <typeparam name="T">数据类型</typeparam>
    /// <param name="key">存储键</param>
    /// <param name="defaultData">默认数据</param>
    /// <returns>加载的数据</returns>
    public static async Task<T> LoadDataAsync<T>(string key, T defaultData = default(T))
    {
        try
        {
            CheckInitialized();
            string filePath = GetFilePath(key);

            if (!_platformAdapter.FileExists(filePath))
            {
                return defaultData;
            }

            string encryptedData = await _platformAdapter.ReadFileAsync(filePath);
            string jsonData = await _encryptionProvider.DecryptAsync(encryptedData);

            return await _serializer.DeserializeAsync<T>(jsonData);
        }
        catch (FileNotFoundException)
        {
            // 文件不存在是预期行为，返回默认值
            return defaultData;
        }
        catch (Exception ex)
        {
            Debug.LogError($"异步加载数据失败: {ex.Message}");
            throw new StorageException("异步加载数据失败", ex);
        }
    }

    /// <summary>
    /// 删除数据
    /// </summary>
    /// <param name="key">存储键</param>
    public static void DeleteData(string key)
    {
        try
        {
            CheckInitialized();
            string filePath = GetFilePath(key);
            if (_platformAdapter.FileExists(filePath))
            {
                _platformAdapter.DeleteFile(filePath);
            }
        }
        catch (Exception ex)
        {
            Debug.LogError($"删除数据失败: {ex.Message}");
            throw new StorageException("删除数据失败", ex);
        }
    }

    /// <summary>
    /// 异步删除数据
    /// </summary>
    /// <param name="key">存储键</param>
    public static async Task DeleteDataAsync(string key)
    {
        try
        {
            CheckInitialized();
            string filePath = GetFilePath(key);
            if (_platformAdapter.FileExists(filePath))
            {
                await _platformAdapter.DeleteFileAsync(filePath);
            }
        }
        catch (Exception ex)
        {
            Debug.LogError($"异步删除数据失败: {ex.Message}");
            throw new StorageException("异步删除数据失败", ex);
        }
    }

    /// <summary>
    /// 检查数据是否存在
    /// </summary>
    /// <param name="key">存储键</param>
    /// <returns>是否存在</returns>
    public static bool HasData(string key)
    {
        try
        {
            CheckInitialized();
            string filePath = GetFilePath(key);
            return _platformAdapter.FileExists(filePath);
        }
        catch (Exception ex)
        {
            Debug.LogError($"检查数据存在失败: {ex.Message}");
            return false;
        }
    }

    /// <summary>
    /// 异步检查数据是否存在
    /// </summary>
    /// <param name="key">存储键</param>
    /// <returns>是否存在</returns>
    public static async Task<bool> HasDataAsync(string key)
    {
        try
        {
            CheckInitialized();
            string filePath = GetFilePath(key);
            // FileExists本身是快速操作，不需要异步实现
            return await Task.Run(() => _platformAdapter.FileExists(filePath));
        }
        catch (Exception ex)
        {
            Debug.LogError($"异步检查数据存在失败: {ex.Message}");
            return false;
        }
    }

    #endregion

    #region 私有辅助方法

    /// <summary>
    /// 清空所有缓存
    /// </summary>
    private static void ClearAllCaches()
    {
        _intCache.Clear();
        _floatCache.Clear();
        _stringCache.Clear();
        _boolCache.Clear();
        _doubleCache.Clear();
        _longCache.Clear();
        _vector2Cache.Clear();
        _vector3Cache.Clear();
        _vector4Cache.Clear();
        _quaternionCache.Clear();
        _rectCache.Clear();
        _colorCache.Clear();
        _objectCache.Clear();
    }

    /// <summary>
    /// 检查是否已初始化
    /// </summary>
    private static void CheckInitialized()
    {
        if (!_initialized)
            throw new InvalidOperationException("StorageKit has not been initialized. Call Initialize() first.");
    }

    /// <summary>
    /// 验证key是否合法
    /// </summary>
    private static void ValidateKey(string key)
    {
        if (string.IsNullOrWhiteSpace(key))
            throw new ArgumentException("Key cannot be null or empty", nameof(key));

        // 检查key中是否包含路径分隔符或其他非法字符
        if (key.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0)
            throw new ArgumentException($"Key contains invalid characters: {key}", nameof(key));

        // 防止路径遍历攻击
        if (key.Contains("..") || Path.IsPathRooted(key))
            throw new ArgumentException($"Key attempts path traversal: {key}", nameof(key));
    }

    /// <summary>
    /// 获取文件的完整路径
    /// </summary>
    private static string GetFilePath(string key)
    {
        ValidateKey(key);
        return Path.Combine(_storagePath, key + ".dat");
    }

    #endregion
}

/// <summary>
/// StorageKit异常类
/// </summary>
public class StorageException : Exception
{
    public StorageException(string message) : base(message)
    {
    }

    public StorageException(string message, Exception innerException) : base(message, innerException)
    {
    }
}